const nodemailer = require('nodemailer')
const schedule = require('node-schedule')
const fs = require('fs')

/* 秒[0-59] 分[0-59] 时[0-24] 天[1-31] 月[1-12] 周[1-(7|0)] */
/* 设置每周一8点发送上周的统计记录 */
schedule.scheduleJob('0 30 8 * * 1', function () {
  send()
});

/* 获取上周的周一到周日的日期范围 */
function getWeekRangeDate() {
  let currentTime = new Date()
  let year = currentTime.getFullYear()
  let month = currentTime.getMonth()
  let date = currentTime.getDate()
  let day = (currentTime.getDay() || 7) + 7
  let currentMonthDayNums = new Date(year, month + 1, 0).getDate()

  let monday = new Date(year, month + 1, date - day + 1 - currentMonthDayNums)
  let sunday = new Date(year, month + 1, date - day + 7 - currentMonthDayNums)

  return [formatDate(monday, " 0:00:00 AM"), formatDate(sunday, " 11:59:59 PM")]
}

/* 格式化日期格式为 mm/dd/yyyy, hh:mm:ss */
function formatDate(date, suffix) {
  return `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}, ${suffix}`
}

/* 统计数量 */
function statistNum(data) {
  let statistData = {
    useNum: 0,
    checkMailLogsNum: 0,
    exportLogsNum: 0,
    sendMailLogsNum: 0,
  }
  const lastWeekRange = getWeekRangeDate()
  let useNumMap = new Map()
  Object.values(data).forEach(t => {
    for (let [key, value] of Object.entries(t)) {
      if (Object.prototype.toString.call(value) === "[object Array]") {
        value.forEach(m => {
          if (m.time > lastWeekRange[0] && m.time < lastWeekRange[1]) {
            statistData[`${key}Num`]++
            if (!useNumMap.has(t.userName)) {
              useNumMap.set(t.userName, 1)
            }
          }
        })
      }
    }
  })
  statistData.useNum = useNumMap.size
  return `<div style="
      display: flex;
    ">
    <div style="flex: 1; border: 1px solid #333; padding: 5px; text-align: center;">
      上周使用人数
    </div>
    <div style="flex: 1; border: 1px solid #333; padding: 5px; text-align: center;">
      检查邮件次数
    </div>
    <div style="flex: 1; border: 1px solid #333; padding: 5px; text-align: center;">
      导出Word次数
    </div>
    <div style="flex: 1; border: 1px solid #333; padding: 5px; text-align: center;">
      发送邮件次数
    </div>
  </div>
  <div
    style="
    display: flex;
  ">
    <div style="flex: 1; border: 1px solid #333; padding: 5px; text-align: center;">
      ${statistData.useNum}
    </div>
    <div style="flex: 1; border: 1px solid #333; padding: 5px; text-align: center;">
      ${statistData.checkMailLogsNum}
    </div>
    <div style="flex: 1; border: 1px solid #333; padding: 5px; text-align: center;">
      ${statistData.exportLogsNum}
    </div>
    <div style="flex: 1; border: 1px solid #333; padding: 5px; text-align: center;">
      ${statistData.sendMailLogsNum}
    </div>
  </div>`
}

const MAIL = 'yaoxuu@qq.com'
const OPTIONS = {
  host: 'smtp.qq.com',
  port: 587,
  secure: false,
  auth: {
    user: MAIL,
    pass: 'jwwwwyedcsvvdicd'
  }
}
const transporter = nodemailer.createTransport(OPTIONS)

async function send() {
  const filePath = `./data/user.json`
  const data = fs.readFileSync(filePath, 'utf-8')
  const HTML = statistNum(JSON.parse(data))
  await transporter.sendMail({
    from: `【周报系统】上周统计数据：<${MAIL}>`,
    to: `<${MAIL}>`,
    subject: '上周的统计数据新鲜出炉，快来看看多了哪些新用户吧！',
    html: HTML,
    // attachments: [{
    //   filename: `user.json`, // 附件名
    //   path: filePath // 附件路径
    // }]
  }, (err, info) => {
    try {
      if (err) {

      }
    } catch {}
  })
}
